<template>
  <div>
    <input type="file" @change="handleFileChange" />
    <button @click="handleCompare">比较</button>
  </div>
</template>

<script setup>
import { ref } from "vue";
import * as XLSX from "xlsx";
import { saveAs } from "file-saver";

const excelList = [];

const handleFileChange = (event) => {
  const file = event.target.files[0];
  const reader = new FileReader();
  reader.onload = (e) => {
    const data = new Uint8Array(e.target.result);
    const workbook = XLSX.read(data, { type: "array" });
    const firstSheetName = workbook.SheetNames[0];
    const worksheet = workbook.Sheets[firstSheetName];
    const jsonData = XLSX.utils.sheet_to_json(worksheet);
    console.log(jsonData);
    excelList.push(jsonData);
  };
  reader.readAsArrayBuffer(file);
};

const exportToExcel = (dataList) => {
  const ws = XLSX.utils.json_to_sheet(dataList);
  const wb = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(wb, ws, "Sheet1");

  const wbout = XLSX.write(wb, { bookType: "xlsx", type: "binary" });
  function s2ab(s) {
    const buf = new ArrayBuffer(s.length);
    const view = new Uint8Array(buf);
    for (let i = 0; i !== s.length; ++i) view[i] = s.charCodeAt(i) & 0xff;
    return buf;
  }

  saveAs(new Blob([s2ab(wbout)], { type: "application/octet-stream" }), "最新数据.xlsx");
};

const trim = (str) => {
  return str.replace(/\s+/g, "");
};

const handleCompare = () => {
  let fields = [
    "competitive_technology_name",
    "domain",
    "energy_type",
    "scene",
    "technology_name",
  ];
  let changeValues = [
    "competitive_economic_level",
    "competitive_green_level",
    "competitive_intelligence_level",
    "competitive_safety_level",
    "subclass_economic_level",
    "subclass_green_level",
    "subclass_intelligence_level",
    "subclass_safety_level",
  ];
  console.log("excelList", excelList);
  let [sheel1, sheel2] = excelList;
  
  let newArr = sheel1.map((item) => {
    let newObj = {...item};
    let row = sheel2.find((col) =>
      fields.every((field) => {
        return col[field] && item[field] && trim(col[field]) === trim(item[field]);
      })
    );
    
    if (row) {
      console.log("row", row);
      changeValues.forEach((changeField) => {
        newObj[changeField] = row[changeField];
      });
      console.log('newObj',newObj);
    }
    return newObj;
  });
  console.log("newArr", newArr);
  const aaaa = newArr.find(item => item.promoting_id === '1804714577774788608')
  console.log("aaaa", aaaa);
  exportToExcel(newArr);
};
</script>
